package com.qudian.pay.schedule.common;

import java.util.Date;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.impl.JobDetailImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanNameAware;
import com.qudian.pay.schedule.model.TaskModel;
import com.qudian.pay.schedule.service.IScheduleService;

public class CommonJobDetail extends JobDetailImpl implements BeanNameAware, Job {
	
	private static final long serialVersionUID = 104736465885209127L;
	
	private static Logger logger = LoggerFactory.getLogger(CommonJobDetail.class);
	
	private String beanName;
	
	private static final String GROUP_KEY = "GROUP_KEY";
	
	private static final String UUID_KEY = "UUID_KEY";
	
	private static final String TASK_TAG_KEY = "TASK_TAG_KEY";
	
	private static final String SCHEDULE_SERVICE_KEY = "SCHEDULE_SERVICE_KEY";
	
	public CommonJobDetail() {
		super.setJobClass(getClass());
	}
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
		logger.info(new Date() + ":  job begin...  group:" 
				+ jobDataMap.get(GROUP_KEY) + "   uuid:"
				+ jobDataMap.get(UUID_KEY) 
				+ " taskName:" + jobDataMap.get(TASK_TAG_KEY));
		String group = String.valueOf(jobDataMap.get(GROUP_KEY));
		String UUID = String.valueOf(jobDataMap.get(UUID_KEY));
		String taskTag = String.valueOf(jobDataMap.get(TASK_TAG_KEY));
		IScheduleService scheduleService = (IScheduleService) jobDataMap.get(SCHEDULE_SERVICE_KEY);
		TaskModel taskModel = new TaskModel();
		taskModel.setGroup(group);
		taskModel.setUuid(UUID);
		taskModel.setTaskTag(taskTag);
		scheduleService.sendMsg(taskModel);
	}
	
	@Override
	public void setBeanName(String name) {
		this.beanName = name;
		super.setName(name);
		super.setGroup("DEFAULT");
	}
	
	public String getBeanName() {
		return this.beanName;
	}
	
	public void setGroup(String group) {
		super.getJobDataMap().put(GROUP_KEY, group);
	}
	
	public void setUuid(String uuid) {
		super.getJobDataMap().put(UUID_KEY, uuid);
	}
	
	public void setTaskTag(String taskTag) {
		super.getJobDataMap().put(TASK_TAG_KEY, taskTag);
	}
	
	public void setScheduleService(IScheduleService scheduleService) {
		super.getJobDataMap().put(SCHEDULE_SERVICE_KEY, scheduleService);
	}
}
